//
//  ByBigImageView.m
//  beibei_ios
//
//  Created by justiOS on 16/7/2.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByBigImageView.h"
#import "ByBigImageViewController.h"
#define KMarginWidth 10

@implementation ByBigImageView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
    }
    
    return self;
}

- (void)setImgAry:(NSArray *)imgAry {
    
    if (self.subviews) {
        for (UIView *view in self.subviews) {
            [view removeFromSuperview];
        }
    }
    // [:f002}
    
    if (_imgAry != imgAry) {
        _imgAry = imgAry;
    }
    if (_imgAry.count == 0 || _imgAry == nil) {
    }
    else {

        // 创建图片视图
        CGFloat x, y, width, height;
        width = (SCREEN_WIDTH - 4 * KMarginWidth) / 3;
        height = width;
        for (int i = 0; i < _imgAry.count; i ++) {
//            y = KMarginWidth + i / 3 * (height + KMarginWidth);
//            x = KMarginWidth + i % 3 * (width + KMarginWidth);
            x = (i % 3) * (width + 10);
            y = (i / 3) * (height + 10);
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
            imgView.userInteractionEnabled = YES;
            imgView.tag = 100 + i;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_pushToBigImgViewVC:)];
            [imgView addGestureRecognizer:tap];
            
            // 大图
            [self addSubview:imgView];
            
            // 加载网络图片
            NSURL *url = [NSURL URLWithString:imgAry[i]];
            [imgView setImageWithURL:url placeholderImage:DEFAULT_IMAGE];
            __weak UIImageView *w_imgView = imgView; // 防止循环调用
            [imgView setImageWithURL:[NSURL URLWithString:_imgAry[i]] placeholderImage:DEFAULT_IMAGE completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                __strong UIImageView *s_imgView = w_imgView;
                if (image == nil) {
                    s_imgView.image = DEFAULT_IMAGE;
                } else {
                    // 设置为长方形的图片
                    s_imgView.image = [image getCenterRectangleImage];
                }
            }];
            
        }
        
    }
    
}


- (void)_pushToBigImgViewVC:(UITapGestureRecognizer *)tap {
    
    ByBigImageViewController *vc = [[ByBigImageViewController alloc] init];
    vc.imageData = self.imgAry;
    NSInteger index = tap.view.tag - 100;
    vc.indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    
    [self.viewController presentViewController:vc animated:YES completion:nil];
}

@end
